package task;

import static java.util.concurrent.TimeUnit.SECONDS;

import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class Sleepy {

    private static final Logger LOGGER = LoggerFactory.getLogger(Sleepy.class);

    protected static final int NUM_THREADS = 10;

    private static final AtomicInteger COUNTER = new AtomicInteger();

    private static final Random RANDOM = new Random();

    private final int id;

    private final int timeout;

    protected Sleepy() {
	id = COUNTER.incrementAndGet();
	timeout = RANDOM.nextInt(NUM_THREADS) + 1;
    }

    protected Integer process() throws ExecutionException {
	LOGGER.info("Starting " + this + "...");
	try {
	    SECONDS.sleep(timeout);

	    LOGGER.info("Finished " + this + " after " + timeout + " seconds.");

	    return timeout;
	} catch (InterruptedException ei) {
	    LOGGER.warn("Aborted " + this + " in less than " + timeout + " seconds!");
	    Thread.currentThread().interrupt();
	    throw new ExecutionException("Interrupted!", ei);
	}
    }

    @Override
    public String toString() {
	return getClass().getSimpleName() + " " + id;
    }
}
